package ace.module.stock.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.core.utils.SystemClockUtils;
import ace.cmp.util.AceAssertUtils;
import ace.module.common.core.impl.manager.impl.AbstractEntityOfAppManager;
import ace.module.stock.api.model.dto.WmsStockBatchRecordDto;
import ace.module.stock.core.impl.dao.entity.WmsStockBatchRecord;
import ace.module.stock.core.impl.dao.repository.WmsStockBatchRecordRepository;
import ace.module.stock.core.impl.manager.WmsStockBatchRecordManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 库存变更批次号记录,保存90天 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class WmsStockBatchRecordManagerImpl
    extends AbstractEntityOfAppManager<WmsStockBatchRecord, Long, WmsStockBatchRecordDto>
    implements WmsStockBatchRecordManager {

  private final WmsStockBatchRecordRepository wmsStockBatchRecordRepository;

  @Override
  public WmsStockBatchRecord build(Long wmsAppId, String batchSn) {
    return WmsStockBatchRecord.builder()
        .id(this.getNewId())
        .wmsAppId(wmsAppId)
        .sn(batchSn)

        .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
        .createTime(SystemClockUtils.currentTimeMillis())
        .updateTime(SystemClockUtils.currentTimeMillis())
        .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
        .build();
  }

  @Override
  public void checkNotExistBatchSnByWmsApIdAndBatchSn(Long wmsAppId, String batchSn) {
    long count = this.wmsStockBatchRecordRepository.countByWmsAppIdAndSnAndDeleteFlag(wmsAppId, batchSn, CoreConstant.DELETE_FLAG_NOT);
    AceAssertUtils.isTrue(count > 0, "[%s]重复的操作流水号", batchSn);
  }

  @Override
  public String getNewSn() {
    return this.getNewId().toString();
  }

  @Override
  public String getDefaultSnOrNewSn(String defaultBatchSn) {
    return StringUtils.isNotEmpty(defaultBatchSn) ? defaultBatchSn : this.getNewSn();
  }
}
